//
//  ClubSetupViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/30.
//

import UIKit

class ClubSetupViewController: ClubBaseViewController, UITextFieldDelegate {

    private let bgView = c_make_ex(UIImageView.self)
        .image("Login_bg").mode(.scaleAspectFill).end()
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let logoImageView = c_make_ex(UIImageView.self)
        .image("Login_logo").mode(.scaleAspectFill).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("账号注册，体验更多功能").color("#17181A").font(24.font_semiBold).end()
    private let phoneTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入手机号码").end()
    private let passwordTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入6~12位密码").end()
    private let rePasswordTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("再次输入密码").end()
    private let inviteTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("邀请码（若没有邀请码可不填）").end()
    private let showOneButton = c_make_ex(UIButton.self)
        .image("Login_hidden").image("Login_show", state: .selected).end()
    private let showTwoButton = c_make_ex(UIButton.self)
        .image("Login_hidden").image("Login_show", state: .selected).end()
    private let setupButton = c_make_ex(UIButton.self)
        .bgColor("#FFAA62").corner(22).color(.white)
        .text("注 册").end()
    private let checkButton = c_make_ex(UIButton.self)
        .image("Login_checkNor").image("Login_checkSel", state: .selected).end()
    private lazy var activeLabel    = ActiveLabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            bgView
            backButton
            titleLabel
            logoImageView
            phoneTextfield
            passwordTextfield
            rePasswordTextfield
            inviteTextfield
            showOneButton
            showTwoButton
            setupButton
            checkButton
            activeLabel
        }
        
        bgView.fillContainer()
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.leading(16).top(.navi_height + 40)
        logoImageView.trailing(0).top(.statusHeight + 4).height(187).width(142)
        phoneTextfield.leading(16).trailing(16).height(50)
        phoneTextfield.Top == titleLabel.Bottom + 50
        passwordTextfield.leading(16).trailing(16).height(50)
        passwordTextfield.Top == phoneTextfield.Bottom + 24
        rePasswordTextfield.leading(16).trailing(16).height(50)
        rePasswordTextfield.Top == passwordTextfield.Bottom + 24
        inviteTextfield.leading(16).trailing(16).height(50)
        inviteTextfield.Top == rePasswordTextfield.Bottom + 24
        setupButton.leading(16).trailing(16).height(44)
        setupButton.Top == inviteTextfield.Bottom + 40
        checkButton.leading(20).size(14)
        checkButton.Top == setupButton.Bottom + 16
        activeLabel.leading(38).height(20)
        activeLabel.CenterY == checkButton.CenterY
        
        
        phoneTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            leftImageV.image = "Login_phone".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        passwordTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            leftImageV.image = "Login_password".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.isSecureTextEntry = true
            v.delegate = self
        }
        rePasswordTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            leftImageV.image = "Login_password".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.isSecureTextEntry = true
            v.delegate = self
        }
        inviteTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 16, width: 24, height: 24))
            leftImageV.image = "Login_InvitationCode".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        configActiveStyle()
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        checkButton.addTarget(self, action: #selector(clickCheckButton), for: .touchUpInside)
        setupButton.addTarget(self, action: #selector(clickSetupButton), for: .touchUpInside)
    }
    
    private func configActiveStyle() {
        let customType = ActiveType.custom(pattern: "《乐玩用户协议》")
        let customType1 = ActiveType.custom(pattern: "《隐私政策》")
        activeLabel.isShowUnderLine = false
        activeLabel.font = 12.font_medium
        activeLabel.numberOfLines = 0
        activeLabel.textAlignment = .left
        activeLabel.enabledTypes = [customType, customType1]
        activeLabel.text = "同意《乐玩用户协议》和《隐私政策》"
        activeLabel.textColor = "#323233".toColor
        activeLabel.customColor[customType] = "#FF8319".toColor
        activeLabel.customColor[customType1] = "#FF8319".toColor
        
        activeLabel.handleCustomTap(for: customType) { [weak self] str in
            let urlString = RaeRequestParameterConfig.shared.baseUrlStr + "ct=zhanwu&ac=agreement&id=1&language=0"
            let webView = ClubWebViewController()
            webView.urlString = urlString
            webView.titleName = "用户协议"
            self?.navigationController?.pushViewController(webView, animated: true)
        }
        activeLabel.handleCustomTap(for: customType1) { [weak self] str in
            let urlString = RaeRequestParameterConfig.shared.baseUrlStr + "ct=zhanwu&ac=agreement&id=2&language=0"
            let webView = ClubWebViewController()
            webView.urlString = urlString
            webView.titleName = "隐私协议"
            self?.navigationController?.pushViewController(webView, animated: true)
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 当前文本
        let currentText = textField.text ?? ""
        // 输入后的文本
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        var maxLength = 11
        if textField == passwordTextfield {
            maxLength = 12
        }
        // 检查输入后的文本是否超过最大长度
        return updatedText.count <= maxLength
    }
    
}

//MARK: action
extension ClubSetupViewController {
    
    
    @objc private func clickSetupButton(){
        
        var inviteCode = ""
        if !checkButton.isSelected {
            "请先阅读并且同意用户协议以及隐私协议".toast_error
            return
        }
        guard let phoneNum = phoneTextfield.text, phoneNum.isValidPhoneNumber else {
            "请输入正确的手机号".toast_error
            return
        }
        guard let password = passwordTextfield.text, password.validatePassword() else {
            "请输入6~12为密码".toast_error
            return
        }
        guard let rePassword = rePasswordTextfield.text, rePassword.validatePassword() else {
            "请再次输入密码".toast_error
            return
        }
        if password != rePassword {
            "两次密码输入不一致".toast_error
            return
        }
        if let inviteC = inviteTextfield.text, inviteC.count > 0 {
            inviteCode = inviteC
        }
        
        let timeStr = String(Date().toTimeStamp())
        let sign = phoneNum + password + timeStr + "fsd213ewdsadqwe2121213edsad"
        let signMd5 = RaeRequestParameterConfig.shared.md5HexDigest(sign)
        
        Task{

            let models = await network.request(.register(user_name: phoneNum, passwd: password, t: timeStr, sign: signMd5, invite: inviteCode), type: ClubLoginModel.self)
            if let model = models.model, models.isSuccess {
                "注册成功".toast_success
                UserDefaultsManager.setString(model.value, forKey: .uid)
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    @objc private func clickCheckButton(){
        
        checkButton.isSelected = !checkButton.isSelected
    }
}
